<?php
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\controller\user\send;

use think\facade\Db;
use app\BaseController;
use app\wework\controller\Base;
use app\wework\model\QyWechatApi;
use app\wework\model\Basemodel;
use think\facade\Session;
use think\facade\Log;
use app\wework\model\user\send\MassSendModel;
include "../extend/PHPExcel/php-excel.class.php";

class MassSend extends Base
{
	/*
	* 客户群发列表
	*/
    public function index(){
		$page = $this->req->param("page")?:1;
        $size = $this->req->param("size")?:10;
		$times = $this->req->param("times");
		$res = MassSendModel::getList($page,$size,$times);

    	return success('客户群发列表',$res);
    }

    public function getSize(){
        $staffer = $this->req->param("staffer");
        if(!$staffer)$staffer = MassSendModel::getAlls();
        $customer_status = $this->req->param("customer_status");
        $customer_gender = $this->req->param("customer_gender");
        $groups = $this->req->param("groups");
        $tags = $this->req->param("tags");
        $times = $this->req->param("times");
        $exclude_tags = $this->req->param("exclude_tags");
        if($customer_status == 2)$externalList = MassSendModel::externalList($staffer,$customer_gender,$groups,$tags,$exclude_tags,$times);
        if($customer_status == 1)$externalList = MassSendModel::externalLists($staffer);

        return success('总人数',count($externalList));
    }


    /**
	 * 添加群发
	 * @param $staffer 选择员工列表 ALL为全部(取消)
	 * @param $customer_status 选择客户，1为全部客户，2为筛选客户
	 * @param $customer_gender 客户性别：1为全部性别，2为男性，3为女性，4为未知性别   
	 * @param $groups 群聊筛选，群聊集合
	 * @param $tags 标签筛选：标签集合
	 * @param $exclude_tags 排除标签筛选：标签集合
	 * @param $repetition_status 客户去重，1为开启，2为关闭
	 * @param $content 群发内容
	 * @param $adjunct_data 附件内容
	 * @param $send_status 群发规则，1为立即群发，2为定时群发
	 * @param $send_time 群发时间
	 * @param 
	 * @param 暂时没做详情数据
	 * @return 
	 */

    public function addMsg(){
 		$wid = Session::get('wid');
        $staffer = $this->req->param("staffer");
        if(!$staffer)$staffer = MassSendModel::getAlls();
        $customer_status = $this->req->param("customer_status");
    	$customer_gender = $this->req->param("customer_gender");
    	$groups = $this->req->param("groups");
    	$tags = $this->req->param("tags");
    	$times = $this->req->param("times");
    	$exclude_tags = $this->req->param("exclude_tags");
    	$repetition_status = $this->req->param("repetition_status");
    	$content = $this->req->param("content");
    	$adjunct_data = $this->req->param("adjunct_data");
    	$send_status = $this->req->param("send_status");
    	$send_time = $this->req->param("send_time");
    	$addMsg = MassSendModel::addMsg($staffer,$customer_status,$customer_gender,$groups,$tags,$exclude_tags,$times,$repetition_status,$content,$adjunct_data,$send_status,$send_time);
    	if($send_status == 1){
    		$msg = ["content"=>$content];
    		$attachments = MassSendModel::assembleOther($adjunct_data,$wid);
    		if($customer_status == 2) $externalList = MassSendModel::externalList($staffer,$customer_gender,$groups,$tags,$exclude_tags,$times,$repetition_status);
    		if($customer_status == 1) $externalList = MassSendModel::externalLists($staffer,$repetition_status);
            foreach($externalList as $value){
                $arr[$value["staff_id"]]["staff_id"] = $value["staff_id"];
                $arr[$value["staff_id"]]["userid"] = $value["userid"];
                $arr[$value["staff_id"]]["externalList"][] = $value["external_userid"];
            }
    		if($repetition_status == 1){
    			foreach($arr as $value){
                    if(count($value["externalList"])){
        				$res = QyWechatApi::addMsgTemplate($wid,$value["externalList"],$value["userid"],$msg,$attachments);
        				if($res["errcode"] == 0){
        					MassSendModel::addMsgid($value["staff_id"],$addMsg,$res["fail_list"],$res["msgid"],2,count($value["externalList"]));
        				}
                    }else{
                        MassSendModel::addMsgid($value["staff_id"],$addMsg,NULL,NULL,3);
                    }
    			}
    		}else{
    			if($customer_status == 2){
    				$arr = [];
    				foreach($externalList as $value){
                        $arr[$value["staff_id"]]["staff_id"] = $value["staff_id"];
	    				$arr[$value["staff_id"]]["userid"] = $value["userid"];
	    				$arr[$value["staff_id"]]["externalList"][] = $value["external_userid"];
	    			}
	    			foreach($arr as $value){
                        if(count($value["externalList"])){
                            $res = QyWechatApi::addMsgTemplate($wid,$value["externalList"],$value["userid"],$msg,$attachments);
                            if($res["errcode"] == 0){
                                MassSendModel::addMsgid($value["staff_id"],$addMsg,$res["fail_list"],$res["msgid"],2,count($value["externalList"]));
                            }
                        }else{
                            MassSendModel::addMsgid($value["staff_id"],$addMsg,NULL,NULL,3);
                        }
	    			}
    			}else{
    				$arr = MassSendModel::getAll($staffer);
    				foreach($arr as $value){
                        if($value["detail_count"] >= 1){
                            $res = QyWechatApi::addMsgTemplate($wid,NULL,$value["userid"],$msg,$attachments);
                            MassSendModel::addMsgid($value["id"],$addMsg,$res["fail_list"],$res["msgid"],2,$value["detail_count"]);
                        }else{
                            MassSendModel::addMsgid($value["id"],$addMsg,NULL,NULL,3);
                        }
    				}
    			}
    		}
            $msgUpd = MassSendModel::msgUpd($addMsg);
    	}
    	return success('添加群发成功',$addMsg);
    }

    /**
    * 客户详情 初始化基本数据
    */
    public function getMsg(){
        $id = $this->req->param("id");
        if(!$id) return error("参数错误");
        $msg = MassSendModel::getMsg($id);
        $msg["detail"] = MassSendModel::getData($id);

        return success('群发详情',$msg);
    }

    public function downexcel(){
        $page = $this->req->param("page")?:1;
        $size = $this->req->param("size")?:10;
        $id = $this->req->param("id");
        $wid = $this->req->param("wid");
        $is_customer = $this->req->param("is_customer");
        if(!$id && !$is_customer) return error("参数错误");
        if($is_customer == 1){
            $type = $this->req->param("type")?:0;
            $res = MassSendModel::detailCustomer($page,$size,$id,$type,NULL,$wid);
            $res = MassSendModel::detailUser($page,$size,$id,$type,NULL,$wid);
            if(!$res["count"])return error("没有数据");
            $arr = [
                0 => ['成员名称','所属成员','推送状态']
            ];
            $i = 1;
            foreach($res["item"] as $value){
                $arr[$i]["成员名称"] = $value["name"];
                $arr[$i]["所属成员"] = $value["staff_name"];
                if($value["status"] == 0)$arr[$i]["推送状态"] = "未发送";
                if($value["status"] == 1)$arr[$i]["推送状态"] = "已发送";
                if($value["status"] == 2)$arr[$i]["推送状态"] = "发送失败-因客户不是好友导致发送失败";
                if($value["status"] == 3)$arr[$i]["推送状态"] = "发送失败-因客户已经收到其他群发消息导致发送失败";
                $i++;
            }
            return success("res",$res);
        }else{
            $type = $this->req->param("type")?:1;
            $res = MassSendModel::detailUser($page,$size,$id,$type,NULL,$wid);
            if(!$res["count"])return error("没有数据");
            $arr = [
                0 => ['员工名称','发送客户数量','推送状态']
            ];
            $i = 1;
            foreach($res["item"] as $value){
                $arr[$i]["员工名称"] = $value["name"];
                $arr[$i]["发送客户数量"] = $value["send_size"];
                if($value["status"] == 1)$arr[$i]["推送状态"] = "已发送";
                if($value["status"] == 2)$arr[$i]["推送状态"] = "未发送";
                if($value["status"] == 3)$arr[$i]["推送状态"] = "发送失败-该成员客户中没有符合筛选条件的客户";
                $i++;
            }

            $str = "客户群发-数据统计-成员详情";
            if($type == 1)$str .= "-全部成员";
            if($type == 2)$str .= "-已发送成员";
            if($type == 3)$str .= "-未发送成员";
            if($type == 4)$str .= "-发送失败成员";
        }
        $xls = new \Excel_XML('utf-8', false, '数据导出');
        $xls->addArray($arr);
        $xls->generateXML($str.date('Y-m-d H:i:s'),time());
        exit();
    }

    /**
    * 客户详情 获取员工数据
    */
	public function detailUser(){
        $page = $this->req->param("page")?:1;
        $size = $this->req->param("size")?:10;
		$type = $this->req->param("type")?:1;
        $id = $this->req->param("id");
        $name = $this->req->param("name");
        if(!$id) return error("参数错误");
		$msg = MassSendModel::detailUser($page,$size,$id,$type,$name);

		return success('群发成员详情',$msg);
	}

    /**
    * 客户详情 获取
    */
    public function detailCustomer(){
        $page = $this->req->param("page")?:1;
        $size = $this->req->param("size")?:10;
        $name = $this->req->param("name");
        $type = $this->req->param("type");
        $id = $this->req->param("id");
        $msg = MassSendModel::detailCustomer($page,$size,$id,$type,$name);
        
        return success('群发客户详情',$msg);
    }

    //提醒全部
    public function alertCustomers(){
        $wid = Session::get('wid');
        $id = $this->req->param("id");
        if(!$id) return error("参数错误");
        $msg = MassSendModel::getMsg($id);
        $detailList = MassSendModel::getDetailList($id);
        foreach($detailList as $value){
            $user = MassSendModel::getUser($value["staff_id"]);
            $str = "【任务提醒】有新的任务啦！";
            $str .= "<br/>";
            $str .= "<br/>";
            $str .= "任务类型：客户群发任务";
            $str .= "<br/>";
            $str .= "<br/>";
            $str .= "客户数量：".$value["send_size"];
            $str .= "<br/>";
            $str .= "<br/>";
            $str .= "创建时间：".$msg["ctime"];
            $str .= "<br/>";
            $str .= "<br/>";
            $str .= "可前往【客户联系】中确认发送，记得及时完成哦";
            $res = QyWechatApi::sendText($wid,$user["userid"],$str);
            if($res["errcode"] != 0){
                return error("错误",$res);
            }
        }
        return success('提醒成功');
    }


    //单独提醒
    public function alertCustomer(){
        $wid = Session::get('wid');
        $id = $this->req->param("id");
        $staff_id = $this->req->param("staff_id");
        if(!$staff_id || !$id) return error("参数错误");
        $user = GroupSendModel::getUser($staff_id);
        $msg = GroupSendModel::getMsg($id);
        $size = GroupSendModel::getStaffSize($staff_id,$id);
        $str = "【任务提醒】有新的任务啦！";
        $str .= "<br/>";
        $str .= "<br/>";
        $str .= "任务类型：客户群发任务";
        $str .= "<br/>";
        $str .= "<br/>";
        $str .= "客户数量：".$size["send_size"];
        $str .= "<br/>";
        $str .= "<br/>";
        $str .= "创建时间：".$msg["ctime"];
        $str .= "<br/>";
        $str .= "<br/>";
        $str .= "可前往【客户联系】中确认发送，记得及时完成哦";
        $res = QyWechatApi::sendText($wid,$user["userid"],$str);
        return success('提醒成功',$res);
    }

    public function sync(){
        $wid = Session::get('wid');
        $id = $this->req->param("id");
        if($id)$where["pid"] = $id;
        $where["status"] = 2;
        $where["wid"] = $wid;
        $msgidList = Db::table('kt_wework_customermsgid')->where($where)->select()->toArray();
        $mh = curl_multi_init();
        $conn = [];
        $res = [];
        $url = $this->req->domain()."/wework/user/send/syncs";
        for ($i=0;$i<count($msgidList);$i++) {
            $data = http_build_query(["msg"=>$msgidList[$i],"wid"=>$wid]);
            $conn[$i]=curl_init($url);
            curl_setopt($conn[$i],CURLOPT_RETURNTRANSFER,1); //如果成功只将结果返回，不自动输出任何内容
            curl_setopt($conn[$i],CURLOPT_TIMEOUT,0);
            curl_setopt($conn[$i], CURLOPT_POSTFIELDS, $data); //post 传参
            curl_multi_add_handle ($mh,$conn[$i]);
        }
        do { $n=curl_multi_exec($mh,$active); }
        while ($active);
        $result = true;
        for ($i=0;$i<count($msgidList);$i++) {
            $res[$i]=curl_multi_getcontent($conn[$i]);
            curl_close($conn[$i]);
            if($res[$i] != 1){
                $result = false;
            }
        }
        if($result){
            $ids = (array_column($msgidList, "pid"));
            Db::table('kt_wework_customermsg')->where(["id"=>$ids])->update(["update_time"=>date("Y-m-d H:i:s")]);
        }

        return success("同步成功");
    }

    public function syncs(){
        $msg = $_POST["msg"];
        $wid = $msg["wid"];
        $user = MassSendModel::getUser($msg["staff_id"]);
        $res = QyWechatApi::getGroupmsgSendResult($wid,$user["userid"],$msg["msgid"]);
        if($res["errcode"] != 0)return error("接口错误");
        MassSendModel::addDetail($res["send_list"],$wid,$msg);
        if(count($res["send_list"])) $msgSet = MassSendModel::msgSet($msg,count($res["send_list"]));

        return success("同步成功");
    }

}
